﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using WenSkin.Controls;

namespace WenFrame.UserControls.UserAdmin
{
    public partial class UserAdminUserControl : WenUserControl
    {
        private WenSkin.SQL.SqlConnect SqlConnect = new WenSkin.SQL.SqlConnect();

        public UserAdminUserControl()
        {
            InitializeComponent();
            wenDataGridView1.AutoGenerateColumns = false;
            RedataAsync();
            ReComboBoxdataAsync();
            new WenUserControlPower(this).SetPower();
        }

        private async void RedataAsync(string username = "")
        {
            string sql = $"select * from w_user where Name like N'%{username}%'";
            wenDataGridView1.DataSource = await SqlConnect.SqlDataTableAsync(sql);
        }

        private async void ReComboBoxdataAsync()
        {
            string sql = $"select UserControlName,UserControlText,PowerName from w_user_power_group";
            DataTable dt = await SqlConnect.SqlDataTableAsync(sql);

            var gs = dt.Rows.Cast<DataRow>().GroupBy(q => q["UserControlName"]);

            foreach (var item in gs)
            {
                comboBox1.Items.Add(new ComBoxItem(item.First()["UserControlText"]?.ToString(), item.First()["UserControlName"]?.ToString(), item.ToArray()));
            }

            comboBox1.SelectedIndex = 0;
        }

        private string GetUserName()
        {
            return wenDataGridView1.CurrentCell != null ? wenDataGridView1.Rows[wenDataGridView1.CurrentCell.RowIndex]?.Cells["UserName"].Value?.ToString() : null;
        }
        class ComBoxItem
        {
            public ComBoxItem(string text, string tag, DataRow[] powers)
            {
                Text = text;
                Tag = tag;
                Powers = powers;
            }

            public string Text { get; set; }

            public string Tag { get; set; }
            public DataRow[] Powers { get; set; }
            
            public List<string> GetPowers()
            {
                List<string> ps = new List<string>();
                foreach (DataRow dr in Powers)
                {
                    ps.Add(dr["PowerName"]?.ToString());
                }
                return ps;
            }
            public override string ToString()
            {
                return Text;
            }
        }


        private List<CheckBox> checkBoxes;

        private void SelectPower(string username, string name)
        {
            string sql = $"select [PowerName],[PowerState] from [w_user_power] where username=N'{username}' and UserControlName=N'{name}'";
            DataTable dt = SqlConnect.SqlDataTable(sql);
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow dr in dt.Rows)
            {
                var com = checkBoxes.Find(q => q.Text.ToUpper() == dr["PowerName"]?.ToString().ToUpper());
                if (com == null)
                    continue;
                com.Checked = (int)dr["PowerState"] == 1;
            }
        }

        private void WenDataGridView1_RowItemClick(object sender, WenDataGridView.DataGridViewRowItemClickEventArgs e)
        {
            string username = GetUserName();
            ComboBox1_SelectedIndexChanged(null, EventArgs.Empty);
        }


        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string username = GetUserName();

            if (string.IsNullOrWhiteSpace(username))
                return;

            flowLayoutPanel1.Controls.Clear();
            checkBoxes = new List<CheckBox>();
            foreach (var item in (comboBox1.SelectedItem as ComBoxItem).GetPowers())
            {
                if (!string.IsNullOrWhiteSpace(item))
                    checkBoxes.Add(new CheckBox() { Text = item });
            }
            flowLayoutPanel1.Controls.AddRange(checkBoxes.ToArray());
            SelectPower(username, (comboBox1.SelectedItem as ComBoxItem).Tag);
        }


        private void ToolStripButton3_Click(object sender, EventArgs e)
        {
            string username = GetUserName();
            string conName = (comboBox1.SelectedItem as ComBoxItem).Tag;
            string text = (comboBox1.SelectedItem as ComBoxItem).Text;

            if (string.IsNullOrWhiteSpace(username))
                return;
            

            StringBuilder st = new StringBuilder();

            st.Append($"delete [w_user_power] where username=N'{username}' and UserControlName=N'{conName}'");

            foreach (var item in flowLayoutPanel1.Controls)
            {
                if (item is CheckBox box)
                {
                    if (box.Checked)
                    {
                        st.Append($"insert into [w_user_power] (username,UserControlName,PowerName,PowerState,UserControlText ) values(N'{username}',N'{conName}',N'{box.Text}',N'1',N'{text}')");
                    }
                }
            }
            SqlConnect.SqlBool(st.ToString());
            this.MsgBoxAsterisk("保存完成");
        }

        private void ToolStripButton4_Click(object sender, EventArgs e)
        {
            using var msg = new TextBoxForm();
            if (msg.ShowDialog() != DialogResult.OK && string.IsNullOrWhiteSpace(msg.Message))
                return;

            string sql = sqlAddUser.TextFormat(msg.Message, UserInfo.UserName);

            MsgBoxAsterisk(SqlConnect.SqlToPrint(sql));
            RedataAsync();
        }

        private void ToolStripButton1_Click(object sender, EventArgs e)
        {
            RedataAsync();
        }

        private void ToolStripButton2_Click(object sender, EventArgs e)
        {
            RedataAsync(soutextbox.Text);
        }

        private void ToolStripButton5_Click(object sender, EventArgs e)
        {
            string username = GetUserName();

            if (string.IsNullOrWhiteSpace(username))
                return;
            string sql = $"update w_user set password=N'123' where Name=N'{username}'";
            SqlConnect.SqlBool(sql);
            MsgBoxAsterisk("重置密码成功，重置后的密码 ：123");
        }

        private void ToolStripButton12_Click(object sender, EventArgs e)
        {
            string username = GetUserName();

            if (string.IsNullOrWhiteSpace(username))
                return;
            string sql = $"update w_user set [del]=0,deltime=getdate(),deluserName=N'{UserInfo.UserName}' where Name=N'{username}'";
            SqlConnect.SqlBool(sql);
            MsgBoxAsterisk("删除用户成功");
            RedataAsync();
        }

        private void ToolStripButton6_Click(object sender, EventArgs e)
        {
            string username = GetUserName();

            if (string.IsNullOrWhiteSpace(username))
                return;
            string sql = $"update w_user set [del]=1,Addtime=getdate(),AddUserName=N'{UserInfo.UserName}',deltime=null,deluserName=null where Name=N'{username}'";
            SqlConnect.SqlBool(sql);
            MsgBoxAsterisk("恢复用户成功");
            RedataAsync();
        }

    }
}
